package cn.acewill.yxd.yunxundian.ui.follow_up;


import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.zyf.vc.ui.PlayVideoActiviy;

import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.adapter.AddPhotoAdapter;
import cn.acewill.yxd.yunxundian.adapter.AddVideoAdapter;
import cn.acewill.yxd.yunxundian.componet.HorizontalListView;
import cn.acewill.yxd.yunxundian.model.t_Feedback_Row;
import cn.acewill.yxd.yunxundian.model.t_Feedback_attachment;
import cn.acewill.yxd.yunxundian.model.tempLostRR;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.ui.MainActivity;
import cn.acewill.yxd.yunxundian.ui.follow_up.nodeStruct.FU_row;
import cn.acewill.yxd.yunxundian.ui.user.ImageViewPagerActivity;
import cn.acewill.yxd.yunxundian.utils.MaterialDialogUtils;

@ContentView(R.layout.fragment_follow_up_item)
public class FollowUpItemFragment extends Fragment implements AdapterView.OnItemClickListener,AdapterView.OnItemLongClickListener {
    protected DbManager db = x.getDb(new YXDAPP().getDaoConfig());
    public static final int FOLLOW_UP_ITEM = 0;
    public static final int FOLLOW_UP_ITEM_PLAN = 1;
    public static final int FOLLOW_UP_ITEM_RESULT = 2;
    private static final String ARG_PARAM1 = "type";
    private static final String ARG_PARAM2 = "node";
    public static final int PHOTO = 0;
    public static final int VIDEO = 1;
    private int type;
    private boolean isMediaEditable;
    private FU_row node;
    private t_Feedback_Row tfr;
    private List<t_Feedback_attachment> tfaList;
    private ProgressDialog progressDialog;
    private int dlCount = 0;

    @ViewInject(R.id.markTitle)
    private TextView markTitle;
    @ViewInject(R.id.ocDesc)
    private TextView ocDesc;
    @ViewInject(R.id.photoText)
    private TextView photoText;
    @ViewInject(R.id.videoText)
    private TextView videoText;
    @ViewInject(R.id.addPhotoListView)
    private HorizontalListView addPhotoListView;
    @ViewInject(R.id.addVideoListView)
    private HorizontalListView addVideoListView;
    @ViewInject(R.id.markDesc)
    private EditText markDesc;
    @ViewInject(R.id.submitInfo)
    private Button submitInfo;
    @ViewInject(R.id.ocText)
    private TextView ocText;
    @ViewInject(R.id.pDesc)
    private TextView pDesc;
    @ViewInject(R.id.pDiv1)
    private View pDiv1;
    @ViewInject(R.id.pDiv2)
    private View pDiv2;
    @ViewInject(R.id.trrDesc)
    private TextView trrDesc;

    private List<String> photoList = new ArrayList<>();
    private List<String> videoList = new ArrayList<>();
    private AddPhotoAdapter photoAdapter;
    private AddVideoAdapter videoAdapter;
    private AddMediaListener addMediaListener;
    private StringBuilder allPhotoFileString = new StringBuilder();
    private StringBuilder allVideoFileString = new StringBuilder();
    private List<MediaFileNode> allFileList = new ArrayList<>();

    private class MediaFileNode {
        public String filePath;
        private boolean isExists;
    }

    public FollowUpItemFragment() {
    }

    public static FollowUpItemFragment newInstance(int type, FU_row node) {
        FollowUpItemFragment fragment = new FollowUpItemFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM1, type);
        args.putSerializable(ARG_PARAM2, node);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            type = getArguments().getInt(ARG_PARAM1);
            node = (FU_row) getArguments().getSerializable(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return  x.view().inject(this, inflater, container);
    }



    @Override
    public void onActivityCreated(Bundle savedInstanceState){
        super.onActivityCreated(savedInstanceState);
        allFileList.clear();
        photoList.clear();
        allPhotoFileString.delete(0,allPhotoFileString.length());
        videoList.clear();
        allVideoFileString.delete(0,allPhotoFileString.length());
        isMediaEditable = false;
        try {
            tfr = db.selector(t_Feedback_Row.class).where("Id", "=", node.id).findFirst();
        } catch (DbException e) {
            e.printStackTrace();
        }
        initTrrInfo();
        markTitle.setText(node.rowName);
        ocDesc.setText(new StringBuilder("督导描述："+node.ocDesc));
        int states = getStates();
        switch(type){
            case FOLLOW_UP_ITEM:
                photoText.setText("评估照片");
                videoText.setText("评估视频");
                pDesc.setText(new StringBuilder("问题分析描述："+node.wentifenxi));
                if(states<2 && node.shopmanid==MainActivity.id){
                    setEditViews("问题分析", node.wentifenxi);
                }else if(states==2 && node.empId==MainActivity.id){
                    setOcEditViews();
                }
                break;
            case FOLLOW_UP_ITEM_PLAN:
                photoText.setVisibility(View.GONE);
                videoText.setVisibility(View.GONE);
                addPhotoListView.setVisibility(View.GONE);
                addVideoListView.setVisibility(View.GONE);
                pDesc.setText(new StringBuilder("行动计划描述："+node.xingdongjihua));
                if(states<2 && node.shopmanid==MainActivity.id){
                    setEditViews("行动计划", node.xingdongjihua);
                }else if(states==2 && node.empId==MainActivity.id){
                    setOcEditViews();
                }
                break;
            case FOLLOW_UP_ITEM_RESULT:
                pDesc.setText(new StringBuilder("整改结果描述："+node.miaoshu));
                if(states<2 && node.shopmanid==MainActivity.id){
                    setEditViews("整改结果", node.miaoshu);
                    isMediaEditable = true;
                }else if(states==2 && node.empId==MainActivity.id){
                    setOcEditViews();
                }
                photoText.setText("整改照片");
                videoText.setText("整改视频");
                initFileList();
                break;
        }
        if(markDesc.getVisibility()==View.VISIBLE){
            markDesc.addTextChangedListener(new TextWatcher() {
                private String oldEditText;

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    //Log.i("onTextChanged", s.toString());
                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                    Log.i("beforeTextChanged", s.toString());
                    oldEditText = s.toString();
                }

                @Override
                public void afterTextChanged(Editable s) {
                    Log.i("TextChangedListener", s.toString());
                    if(!s.toString().equals(oldEditText))
                        saveTfr(s.toString());
                }
            });
        }
    }

    private void setEditViews(String title, String text){
        pDesc.setVisibility(View.GONE);
        ocText.setText(new StringBuilder(title+"："));
        ocText.setVisibility(View.VISIBLE);
        markDesc.setFocusableInTouchMode(true);
        markDesc.setFocusable(true);
        markDesc.setHint("请在此处输入"+title+"描述（最多500字）");
        markDesc.setText(text);
        markDesc.setVisibility(View.VISIBLE);
        if(type == FOLLOW_UP_ITEM_RESULT) {
            submitInfo.setText("提交附件");
            submitInfo.setVisibility(View.VISIBLE);
        }
    }

    private void setOcEditViews(){
        ocDesc.setVisibility(View.GONE);
        pDiv1.setVisibility(View.GONE);
        pDiv2.setVisibility(View.VISIBLE);
        ocText.setText("督导描述：");
        ocText.setVisibility(View.VISIBLE);
        markDesc.setFocusableInTouchMode(true);
        markDesc.setFocusable(true);
        markDesc.setHint("请在此处输入督导描述（最多500字）");
        String ocdStr = tfr!=null ? tfr.getocDesc() : node.ocDesc;
        markDesc.setText(ocdStr);
        markDesc.setVisibility(View.VISIBLE);
        submitInfo.setText("不通过");
        submitInfo.setVisibility(View.VISIBLE);
    }

    private void saveTrrInfo(String files, String desc){
        trrDesc.setText(new StringBuilder("评估描述："+desc));
        if(tfr!=null) {
            tfr.settrrDesc(desc);
            tfr.settrrFiles(files);
            tfr.setisTrrInfoLoaded(1);
            try {
                db.saveOrUpdate(tfr);
            } catch (DbException e) {
                e.printStackTrace();
            }
        }
    }

    private void initTrrInfo(){
        try {
            if (tfr.getisTrrInfoLoaded() != 1) {
                tempLostRR trr = db.selector(tempLostRR.class).where("ID", "=", node.trrid).findFirst();
                if (trr != null) {
                    StringBuilder fileBuff = new StringBuilder();
                    List<String> fileList = new ArrayList<>();
                    fileList.addAll(splitListViewPicString(trr.getJpgStr()));
                    fileList.addAll(splitListViewPicString(trr.getVideoStr()));
                    for(String filePath : fileList){
                        if(fileBuff.length()>0)
                            fileBuff.append(',');
                        fileBuff.append(filePath);
                    }
                    saveTrrInfo(fileBuff.toString(), trr.getDescStr());
                    if(type == FOLLOW_UP_ITEM)
                        initFileList();
                } else {
                    getHttpQuery("loadTrrsByTFBRID",null);
                }
            }else{
                trrDesc.setText(new StringBuilder("评估描述："+tfr.gettrrDesc()));
                if(type == FOLLOW_UP_ITEM)
                    initFileList();
            }
        } catch (DbException e) {
            e.getStackTrace();
        }
    }

    private void initFileList(){
        List<String> fileList = new ArrayList<>();
        if(type == FOLLOW_UP_ITEM) {
            fileList = splitListViewPicString(tfr.gettrrFiles());
        } else if (type == FOLLOW_UP_ITEM_RESULT){
            try {
                tfaList = db.selector(t_Feedback_attachment.class)
                        .where("t_FB_R_ID","=",node.id)
                        .findAll();
                if(tfaList!=null) {
                    for (t_Feedback_attachment tfa : tfaList) {
                        if (tfa.getlocalFilePath() == null || tfa.getlocalFilePath().length() < 5) {
                            if (tfa.getfileName().endsWith(".jpg")) {
                                tfa.setlocalFilePath(pubClass.pictureSavePath + tfa.getfileName());
                            } else if (tfa.getfileName().length() > 4) {
                                tfa.setlocalFilePath(pubClass.videoSavePath + tfa.getfileName());
                            }
                            db.saveOrUpdate(tfa);
                        }
                        fileList.add(tfa.getlocalFilePath());
                    }
                }else{
                    tfaList = new ArrayList<>();
                }
            } catch (DbException e) {
                e.getStackTrace();
            }
        }
        for (String filePath : fileList) {
            MediaFileNode fileNode = new MediaFileNode();
            fileNode.filePath = filePath;
            fileNode.isExists = new File(filePath).exists();
            allFileList.add(fileNode);
        }
        downloadMedia();
    }

    private void initMediaView(){
        for(MediaFileNode fileNode:allFileList) {
            if(fileNode.isExists) {
                if (fileNode.filePath.endsWith(".jpg")) {
                    photoList.add(fileNode.filePath);
                    allPhotoFileString.append(fileNode.filePath).append(",");
                } else if(fileNode.filePath.length()>4){
                    videoList.add(fileNode.filePath);
                    allVideoFileString.append(fileNode.filePath).append(",");
                }
                //Log.i("initMediaView", "["+type+"]"+fileNode.filePath);
            }
        }
        photoAdapter = new AddPhotoAdapter(getActivity(), photoList);
        addPhotoListView.setAdapter(photoAdapter);
        addPhotoListView.setOnItemClickListener(this);
        addPhotoListView.setOnItemLongClickListener(this);
        videoAdapter=new AddVideoAdapter(getActivity(), videoList);
        addVideoListView.setAdapter(videoAdapter);
        addVideoListView.setOnItemClickListener(this);
        addVideoListView.setOnItemLongClickListener(this);
        if(!isMediaEditable && photoList.size()==0){
            photoText.setVisibility(View.GONE);
            addPhotoListView.setVisibility(View.GONE);
        }
        if(!isMediaEditable && videoList.size()==0){
            videoText.setVisibility(View.GONE);
            addVideoListView.setVisibility(View.GONE);
        }
    }

    @Event(value={R.id.submitInfo})
    private void onSubmit(View view){
        int states = getStates();
        if(states==2){
            String descText = markDesc.getText().toString();
            if(!TextUtils.isEmpty(descText)){
                getHttpQuery("deniedTfrByTfrId", descText);
            }else{
                BaseActivity.showAnimaDialog(getActivity(), "督导描述不能为空");
            }
        }else if(states<2){
            upLoadMedia();
        }
    }

    private void getTrrInfoCallback(String result){
        Log.i("getTrrInfoCallback", "type["+type+"]:"+result);
        String[] resArry = result.split("\\|");
        if (resArry[0].equals("200")){
            BaseActivity.showAnimaDialog(getActivity(), "加载评估信息成功");
            StringBuilder fileBuff = new StringBuilder();
            if(!TextUtils.isEmpty(resArry[1])) {
                String[] allFiles = resArry[1].split(";");
                for (String file : allFiles) {
                    if (fileBuff.length() > 0)
                        fileBuff.append(',');
                    if (file.endsWith(".jpg")) {
                        fileBuff.append(pubClass.pictureSavePath).append(file);
                    } else if (file.length() > 4) {
                        fileBuff.append(pubClass.videoSavePath).append(file);
                    }
                }
            }
            String trrDesc = resArry.length>3 ? resArry[3] : "";
            saveTrrInfo(fileBuff.toString(), trrDesc);
            if(type == FOLLOW_UP_ITEM)
                initFileList();
        } else {
            BaseActivity.showAnimaDialog(getActivity(), "加载评估信息失败");
        }
    }

    private void unPassCallback(String result){
        String[] resArry = result.split("\\|");
        if (resArry[0].equals("200")){
            if(tfr != null){
                try {
                    tfr.setstates(111);
                    db.saveOrUpdate(tfr);
                } catch (DbException e) {
                    e.printStackTrace();
                }
            }
            BaseActivity.showAnimaDialog(getActivity(), "不通过提交成功，自动跳转");
            if(getActivity()!=null)
                getActivity().finish();
        } else {
            BaseActivity.showAnimaDialog(getActivity(), "不通过提交失败，请稍后再试");
        }
    }

    private void getHttpQuery(final String task, String otherParams){
        RequestParams params = new RequestParams(pubClass.Server_namehzm);
        params.addQueryStringParameter("task", task);
        if(task.equals("deniedTfrByTfrId")){
            params.addQueryStringParameter("tfrId", Integer.toString(node.id));
            params.addQueryStringParameter("ocdesc", otherParams);
        }else{
            params.addQueryStringParameter("tfbrid", Integer.toString(node.id));
        }
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                switch(task){
                    case "deniedTfrByTfrId":
                        unPassCallback(result);
                        break;
                    case "loadTrrsByTFBRID":
                        getTrrInfoCallback(result);
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                BaseActivity.showAnimaDialog(getActivity(), ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {
                BaseActivity.showAnimaDialog(getActivity(), "链接请求已取消");
            }

            @Override
            public void onFinished() {
            }
        });
    }

    private void downloadMedia(){
        List<String> fileList = new ArrayList<>();
        for(MediaFileNode fileNode:allFileList){
            if(!fileNode.isExists)
                fileList.add(fileNode.filePath);
        }
        if(fileList.size()>0){
            progressDialog=new ProgressDialog(getActivity());
            progressDialog.setMessage("需下载"+fileList.size()+"个文件，请稍候");
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                    return keyCode==KeyEvent.KEYCODE_BACK;
                }
            });
            progressDialog.show();
        } else {
            initMediaView();
            return;
        }

        for(final String filepath:fileList){
            dlCount++;
            final String fileName = filepath.substring(filepath.lastIndexOf("/")+1);
            pubClass.DownLoadFile(pubClass.downLoadUri+fileName,filepath,new Callback.ProgressCallback<File>(){
                @Override
                public void onWaiting() {

                }

                @Override
                public void onStarted() {
                    progressDialog.setMessage(fileName+"正在下载...");
                }

                @Override
                public void onLoading(long total, long current, boolean isDownloading) {
                    if(isDownloading && progressDialog.isShowing()){
                        progressDialog.setProgress((int) (current*100/total));
                    }
                }

                @Override
                public void onSuccess(File result){
                    progressDialog.setMessage(fileName+"下载成功！");
                    for(MediaFileNode fileNode:allFileList){
                        if(fileNode.filePath.equals(filepath)){
                            fileNode.isExists = true;
                            break;
                        }
                    }
                    Log.i("download success", filepath);
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback){
                    progressDialog.setMessage(fileName+"下载失败！");
                    Log.e("download error", fileName+" "+ex.getLocalizedMessage());
                }

                @Override
                public void onCancelled(CancelledException cex) {

                }

                @Override
                public void onFinished() {
                    dlCount--;
                    if(dlCount<=0) {
                        initMediaView();
                        if(progressDialog.isShowing())
                            progressDialog.dismiss();
                        dlCount = 0;
                    }
                }
            });
        }

    }

    private void upLoadMedia(){
        Map<String, Object> map = new HashMap<>();
        map.put("task", "saveFeedBackAttachByTRBRID");
        map.put("tfbrid", node.id);
        File file;
        int count = 0;
        for(t_Feedback_attachment tfa:tfaList){
            if(tfa.getlocalFilePath()!=null && tfa.getlocalFilePath().length()>4 && tfa.getisUploaded()!=1){
                file = new File(tfa.getlocalFilePath());
                if (file.exists()) {
                    map.put("uploadfile" + count, file);
                    count++;
                }
            }
        }
        if(count > 0){
            progressDialog=new ProgressDialog(getActivity());
            progressDialog.setMessage("正在上传图片视频文件，请稍候");
            progressDialog.setCanceledOnTouchOutside(false);
            progressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                    return keyCode==KeyEvent.KEYCODE_BACK;
                }
            });
            progressDialog.show();
            pubClass.UpLoadFile(pubClass.Server_namehzm, map, new pubClass.MyCallBack<String>() {
                @Override
                public void onSuccess(String result) {
                    super.onSuccess(result);
                    String[] resArry = result.split("\\|");
                    if (resArry[0].equals("200")) {
                        try {
                            for(t_Feedback_attachment tfa:tfaList){
                                if(tfa.getlocalFilePath()!=null && tfa.getlocalFilePath().length()>4 && tfa.getisUploaded()!=1){
                                    tfa.setisUploaded(1);
                                }
                            }
                            db.saveOrUpdate(tfaList);
                            tfr.setunULCount(0);
                            db.saveOrUpdate(tfr);
                        } catch (DbException e) {
                            e.printStackTrace();
                        }
                        if (progressDialog.isShowing())
                            progressDialog.dismiss();
                        BaseActivity.showAnimaDialog(getActivity(),"文件上传成功，自动跳转");
                        if(getActivity()!=null)
                            getActivity().finish();
                    } else {
                        if (progressDialog.isShowing()){
                            progressDialog.dismiss();
                            BaseActivity.showAnimaDialog(getActivity(),"文件上传失败，请稍后再试");
                        }
                    }
                }
                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    super.onError(ex, isOnCallback);
                    if (progressDialog.isShowing()){
                        progressDialog.dismiss();
                        BaseActivity.showAnimaDialog(getActivity(),"文件上传失败，请稍后再试");
                    }
                }
            });
        }else{
            BaseActivity.showAnimaDialog(getActivity(),"没有未提交的文件");
        }
    }

    private int getStates() {
        int states = 0;
        switch(type){
            case FOLLOW_UP_ITEM:
                states = (int)Math.floor(node.rowStates/100);
                break;
            case FOLLOW_UP_ITEM_PLAN:
                states = (int)Math.floor(node.rowStates%100/10);
                break;
            case FOLLOW_UP_ITEM_RESULT:
                states = node.rowStates%10;
                break;
        }
        return states;
    }

    private void saveTfr(String descText){
        try {
            if(tfr!=null) {
                int states = getStates();
                Log.i("saveTfr","type = "+type+", states = "+states);
                if(states<3) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
                    String currentTime = sdf.format(new Date()).replace(' ', 'T');
                    tfr.setlastupdate(currentTime);
                }
                if(states==2) {
                    tfr.setocDesc(descText);
                }else if(type == FOLLOW_UP_ITEM){
                    tfr.setwentifenxi(descText);
                    if(states==0)
                        tfr.setstates(node.rowStates+100);
                }else if(type == FOLLOW_UP_ITEM_PLAN){
                    tfr.setxingdongjihua(descText);
                    if(states==0)
                        tfr.setstates(node.rowStates+10);
                }else if(type == FOLLOW_UP_ITEM_RESULT){
                    tfr.setmiaoshu(descText);
                    if(states==0)
                        tfr.setstates(node.rowStates+1);
                }
                db.saveOrUpdate(tfr);
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id){
        switch(parent.getId()){
            case R.id.addPhotoListView:
                //Log.i("FollowUpItemFragment","OnItemClickListener:Photo,position="+position);
                if (position==0) {
                    if(isMediaEditable) {
                        if (photoAdapter.getCount() < 9) {
                            addMediaListener.showPop(PHOTO, allPhotoFileString);
                        } else {
                            BaseActivity.showAnimaDialog(getActivity(), "照片已达最大限制");
                        }
                    }
                } else {
                    StringBuilder jpgStr= new StringBuilder();
                    for (int k=0;k<photoList.size();k++){
                        jpgStr.append(photoList.get(k)).append(",");
                    }
                    startActivity(new Intent(getActivity(),ImageViewPagerActivity.class)
                            .putExtra("filepath", jpgStr.toString())
                            .putExtra("position",position-1));
                }
                break;
            case R.id.addVideoListView:
                //Log.i("FollowUpItemFragment","OnItemClickListener:Video,position="+position);
                if (position==0){
                    if(isMediaEditable) {
                        if (videoAdapter.getCount() <= 1) {
                            addMediaListener.showPop(VIDEO, allVideoFileString);
                        } else {
                            BaseActivity.showAnimaDialog(getActivity(), "视频已达最大限制");
                        }
                    }
                } else {
                    //点击播放
                    startActivity(new Intent(getActivity(),PlayVideoActiviy.class).putExtra("file_path",videoList.get(position-1)).putExtra("code_play",2));
                }
                break;
        }
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id){
        switch(parent.getId()){
            case R.id.addPhotoListView:
                if (position != 0 && isMediaEditable) {
                    t_Feedback_attachment tfa = getTfaByLP(photoList.get(position-1));
                    if(tfa!=null && tfa.getisUploaded()!=1)
                        delMediaListItem(position-1, PHOTO);
                    else
                        BaseActivity.showAnimaDialog(getActivity(), "已上传照片无法删除");
                }
                break;
            case R.id.addVideoListView:
                if (position != 0 && isMediaEditable) {
                    t_Feedback_attachment tfa = getTfaByLP(videoList.get(position-1));
                    if(tfa!=null && tfa.getisUploaded()!=1)
                        delMediaListItem(position-1, VIDEO);
                    else
                        BaseActivity.showAnimaDialog(getActivity(), "已上传视频无法删除");
                }
                break;
        }
        return false;
    }

    public interface AddMediaListener{
        void showPop(int type, StringBuilder allMediaString);
    }

    public void setAddMediaListener(AddMediaListener addMediaListener) {
        this.addMediaListener = addMediaListener;
    }

    @Nullable
    private t_Feedback_attachment getTfaByLP(String localPath){
        for (t_Feedback_attachment tfa : tfaList) {
            if (localPath.equals(tfa.getlocalFilePath()))
                return tfa;
        }
        return null;
    }

    private void saveMediaDb(List<String> mediaList){
        for (String localPath : mediaList) {
            if (getTfaByLP(localPath)==null){
                t_Feedback_attachment tfa = new t_Feedback_attachment();
                tfa.sett_FB_R_ID(node.id);
                tfa.setfileName(localPath.substring(localPath.lastIndexOf("/")+1));
                tfa.setlocalFilePath(localPath);
                tfa.setisUploaded(0);
                if(tfaList!=null)
                    tfaList.add(tfa);
                if(tfr!=null)
                    tfr.setunULCount(tfr.getunULCount()+1);
            }
        }
        try {
            db.saveOrUpdate(tfaList);
            db.saveOrUpdate(tfr);
            //Log.i("saveMediaDb",tfr.toString());
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    private void deleMediaDb(String localPath){
        try {
            if(tfr!=null && tfr.getunULCount()>0){
                tfr.setunULCount(tfr.getunULCount()-1);
                db.saveOrUpdate(tfr);
                //Log.i("deleMediaDb",tfr.toString());
            }
            for (t_Feedback_attachment tfa : tfaList) {
                if (localPath.equals(tfa.getlocalFilePath())) {
                    db.delete(tfa);
                    tfaList.remove(tfa);
                    return;
                }
            }
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    public void setMediaListViewData(int type, StringBuilder fileStr){
        if(type == PHOTO){
            allPhotoFileString = fileStr;
            photoList = splitListViewPicString(fileStr.toString());
            saveMediaDb(photoList);
            photoAdapter.setListData(photoList);
            photoAdapter.notifyDataSetInvalidated();
        }else{
            allVideoFileString = fileStr;
            videoList = splitListViewPicString(fileStr.toString());
            saveMediaDb(videoList);
            videoAdapter.setListData(videoList);
            videoAdapter.notifyDataSetInvalidated();
        }
    }

    public List<String> splitListViewPicString(String fileString) {
        String[] everyPicFile = fileString.split(",");
        List<String> imgList = new ArrayList<>();
        for (String everyPic : everyPicFile) {
            if (!TextUtils.isEmpty(everyPic)) {
                imgList.add(everyPic);
            }
        }
        return imgList;
    }

    private void delMediaListItem(final int position, final int type) {
        String dialogText = type==PHOTO ? "是否删除照片" : "是否删除视频";
        MaterialDialogUtils.showMaterialDialog(getActivity(), dialogText, "确定", "取消", true,false, new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                dialog.dismiss();
                StringBuilder newAllFileList = new StringBuilder();
                if(type==PHOTO) {
                    deleMediaDb(photoList.get(position));
                    photoList.remove(position);
                    for (int i = 0; i < photoList.size(); i++) {
                        newAllFileList.append(photoList.get(i)).append(",");
                    }
                    allPhotoFileString = newAllFileList;
                    photoAdapter.setListData(photoList);
                    photoAdapter.notifyDataSetChanged();
                }else{
                    deleMediaDb(videoList.get(position));
                    videoList.remove(position);
                    for (int i=0;i<videoList.size();i++){
                        newAllFileList.append(videoList.get(i)).append(",");
                    }
                    allVideoFileString=newAllFileList;
                    videoAdapter.setListData(videoList);
                    videoAdapter.notifyDataSetChanged();
                }
            }
        }, new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                dialog.dismiss();
            }
        });
    }
}
